/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode(0);  // 虚拟头节点
        ListNode* cur = dummy;
        int carry = 0;   // 进位
        while(l1 || l2){
            int n1 = l1 ? l1->val : 0;
            int n2 = l2 ? l2->val : 0;
            int num = n1 + n2 + carry;
            ListNode* tmp = new ListNode(num%10);
            cur->next = tmp;
            cur = cur->next;
            if(l1) l1 = l1->next;
            if(l2) l2 = l2->next;
            carry = num / 10;
        }
        if(carry != 0){
            cur->next = new ListNode(carry);
        }
        return dummy->next;
    }
};
